import CommonValidator from "./common-validator";
import TransValidator from "./trans-validator";
import DateValidator from "./date-validator";

import { createCallback } from "./utils/tools";

class ValidatorFactory {
  /** @type {function} 需要加工的校验规则构造函数 */
  validator;
  /** initial prop */
  prop;

  constructor(validator, { prop = "defaultProp" }) {
    this.methods = new validator();
    this.prop = prop;

    this._initCallbacks();
  }

  _createCallback = (method, options = {}) => {
    const ctx = this;

    const errorMsg = options.errorMsg || "error",
      required = options.required || true,
      prop = options.prop || this.prop,
      trigger = options.trigger || "";

    console.log(prop, this.prop);

    const validator = createCallback({
      required,
      prop,
      trigger,
      validator: method.call(ctx, errorMsg),
    });

    return validator;
  };

  _initCallbacks() {
    const checkReg = /^(check)/;
    /** 非空校验函数 */
    this.checkIsNull = (options) =>
      this._createCallback(this.methods.checkIsNull, options);
    /** 生成正则校验函数 */
    Object.getOwnPropertyNames(this.methods).forEach((k) => {
      if (checkReg.test(k)) {
        this[`${k}`] = (options) =>
          this._createCallback(this.methods[k], options);
      }
    });
  }
}

function creatteValidator(validator, options) {
  return new ValidatorFactory(validator, options);
}

const { checkIsNull, checkMobilePhone } = creatteValidator(CommonValidator, {});

console.log([
  checkIsNull({
    prop: "username",
    trigger: "blur",
    required: true,
  }),
  checkMobilePhone({
    prop: "mobile",
    trigger: "input",
    required: true,
  }),
]);

export default creatteValidator;

export {
  /* sub validators */
  CommonValidator,
  TransValidator,
  DateValidator,
  /* ------------------------------------------------ */
  /* utils */
  createCallback,
  /* ------------------------------------------------ */
};
